<template>
    <div class="designer">
        <!-- 头部 -->

        <div class="designer-init" v-if="initing">
            <UxLoading2 v-if="typeof initing == 'boolean'" />
            <p v-else>
                <strong v-text="initing"></strong>
                <button @click="getData($route.query, callback)">Reload</button>
            </p>
        </div>

        <div class="layout-ready" v-else>

            <!-- 渲染区 -->
            <div class="layout-render">

                <!-- 产品名称 -->
                <DesignerProductName class="layout-render-name" :title="title" @changeShape="changeShape()" />
                <!-- 标签 -->
                <DesignerModelTags class="layout-render-tag" v-model="activeModelTag" :spu="spu" />

                <!-- 预览区 -->
                <div class="layout-render-preview">
                    <DesignerModelPanel />
                </div>

                <!-- 模特列表 -->
                <!-- <div class="layout-render-models"><DesignerModelList /></div> -->

                <!-- 颜色 -->
                <div class="layout-render-color">
                    <DesignerColorPanel />
                </div>

                <!-- 价格 -->
                <div class="layout-render-price">
                    <DesignerPriceDetail :sizes="sizes_list" :levelInfo="levelInfo" />
                </div>
            </div>

            <div class="layout-content">

                <!-- 工艺 -->
                <DesignerProcessPanel />

                <!-- 设计区 -->
                <div class="layout-editor">
                    <!-- 裁片tab -->
                    <div class="layout-editor-pieces">
                        <DesignerPiecesPanel :spu="spu" />
                    </div>

                    <!-- 编辑区 -->
                    <div class="layout-editor-flex">
                        <div class="layout-editor-panel">
                            <DesignerEditorPanel :zoom="zoom" :gridline="gridline" />
                        </div>

                        <!-- 一些按钮 -->
                        <div class="layout-editor-button">
                            <!-- 网格按钮 -->
                            <button class="editor-button-gridline" @click="handlerGrid"
                                    v-show="activePieceLarys && activePieceLarys.length > 0"
                                    :class="{ active: gridline }" :title="gridline ? 'Grid off' : 'Grid on'">
                                <svg-icon name="editor-gridline" />
                            </button>
                            <!-- 缩放按钮 -->
                            <button class="editor-button-zoom" @click="handlerScale"
                                    v-show="activePieceLarys && activePieceLarys.length > 0" :class="{ active: zoom }"
                                    :title="zoom ? 'Zoom out' : 'Zoom in'">
                                <svg-icon name="editor-zoom-out" v-if="zoom" />
                                <svg-icon name="editor-zoom-in" v-else />
                            </button>
                        </div>
                    </div>

                    <!-- 提示 -->
                    <DesignerEditorNotify />

                </div>

                <!-- 工具区 -->
                <div class="layout-tooler">
                    <!-- 参数编辑模块 -->
                    <div class="layout-tooler-panel">
                        <DesignerToolerPanel />
                    </div>

                    <!-- 保存按钮 -->
                    <div class="layout-tooler-save" v-show="saveAble">
                        <button @click="saveDraft()" type="primary"
                                :disabled="exceedStitches.length > 0 || exceedColors.length > 0 || oversizeDst.length > 0 || overlapDst.length > 0">Save</button>
                    </div>
                </div>
            </div>

        </div>

        <!-- 绘制过程 -->
        <DesignerSaveDialog ref="saving" />
        <!-- 清晰度弹窗 -->
        <DesignerClarityDialog ref="clarity" />
        <!-- 像素重叠对话框 -->
        <DesignerOverlapDialog ref="overlap" />
        <!-- 离开对话框 -->
        <DesignerLeaveDialog ref="leave" />
        <!-- 切换商品前保存确认对话框 -->
        <DesignerSwitchDialog ref="switch" />
        <!-- 选择商品对话框 -->
        <ProductSelectDialog ref="products" />
        <!-- 设计数据切换商品后覆盖弹窗 -->
        <DesignerApplyDialog ref="apply" />
        <!-- 打开选择图片对话框 -->
        <DesignerMediaDialog ref="dtg_file_dialog" />
        <!-- 打开刺绣框选择弹窗 -->
        <DesignerEmbPlatenDialog :recently-upload="recently_upload" :recently-text="recently_text" />
        <!-- 选择版带 -->
        <DesignerEmbDstSelectDialog ref="emb_file_dialog" :recently-upload="recently_upload" />
        <!-- 编辑上传的版带 -->
        <DesignerEmbDstEditDialog />
        <!-- 编辑文字 -->
        <DesignerEmbTxtEditDialog :recently-text="recently_text" />

    </div>
</template>
<script>
import { mapGetters, mapState } from "vuex";
import DesignManager from "@/utils/DesignManager.js";
import { colors } from "@/utils/EmbroideryPattern.js";
import { getStitchesByBase64 } from "@/utils/EmbroideryDst.js";
import { writeCanvas } from "@/utils/EmbroideryCanvas.js";

export default {
    name: "Designer",
    layout: "layout-designer",
    data () {
        return {
            cache: "", // 缓存
            initing: true,
            callback: null,

            title: "",
            spu: "",
            product_id: "",
            template_id: "",
            sizes_list: [],
            levelInfo: null,
            recently_upload: [],
            recently_text: [],
            gridline: false,
            zoom: null,

        };
    },
    computed: {
        ...mapState("designer", { oversizeDst: "oversize_dst", overlapDst: "overlap_dst", exceedStitches: 'exceed_stitches', exceedColors: 'exceed_colors' }),
        ...mapGetters("designer", {
            models: "getModels",
            platens: "getPlatens",
            pieces: "getPieces",
            colors: "getColors",
            activePiece: "getActivePiece",
            activeSurface: "getActiveSurface",
            activeModel: "getActiveModel",
            activeColor: "getActiveColor",
            necklabelInfo: 'getNecklabelInfo',
            activePieceLarys: "getActivePieceLayers",
            saveAble: "getSaveAble",

        }),
        ...mapGetters({
            isLogin: "getIsLogin",
        }),
        // 当前模特
        activeModelTag: {
            get () {
                let store = this.$store.state.designer || {};
                return store.activeModelTag;
            },
            set (val) {
                this.$store.commit("designer/SET_ACTIVE_MODEL_TAG", val);
            }
        },

    },
    watch: {
        // 切换设计面
        activeSurface () {
            this.zoom = null;
            this.gridline = false;
        },
        // 切换打印区
        activePiece () {
            this.zoom = null;
            this.gridline = false;
        },
        // 打印区图层变化
        activePieceLarys () {
            // 当前设计区的图层
            if (!this.activePieceLarys || this.activePieceLarys.length == 0) {
                this.zoom = null;
                this.gridline = false;
            }
        },
    },
    methods: {
        handlerGrid (e) {
            this.gridline = !this.gridline
            this.blurButton(e)
        },
        handlerScale (e) {
            this.zoom = !this.zoom;
            this.blurButton(e)
        },
        blurButton (e) {
            e && e.target && e.target.blur();
            document.body.focus(); // 将焦点设置回 body
        },
        async getData (query, callback) {
            // let store = this.$store.state.designer || {};
            // let query = def || this.$route.query || {};
            let pid = query.pid || query.id || 0; // 产品id
            let tid = query.tid || 0; // 模板id
            let result = null;


            this.initing = true;
            this.callback = callback

            if (tid) {
                result = (await this.$http("storeTemplate.getTemplate", tid)) || {};
            } else {
                result = (await this.$http("Designer.getInfo", pid)) || {};
            }


            // result.data.platens_opt = [
            //     { code: '1', name: '4*4', width: 1200, height: 1200 },
            //     { code: '2', name: '4*12', width: 1200, height: 3600 },
            //     { code: '3', name: '12*16', width: 3600, height: 4800 }
            // ]

            // result.data.piece_list.map(item => {

            //     if (item.canvas_name == "Front Side") {
            //         item.type = 2
            //         item.optional_platens = '[{"code":"1"},{"code":"2"},{"code":"3"}]'
            //     } else if (item.canvas_name == "Back Side") {
            //         item.type = 2
            //         item.optional_platens = '[{"code":"1"},{"code":"2"},{"code":"3"}]'

            //     } else {
            //         item.type = 1
            //     }

            // })

            if (result.code === 0) {

                const user = this.$store.state.user || {}
                let data = result.data || {};
                let color_list = (data.color_list || []).sort((a, b) => a.sort - b.sort);

                // 设计区列表
                let piece_list = (data.piece_list || []).map((item, index) => {
                    // 字段名都改变了，这里要特别注意！！！！！
                    let piece = {
                        id: item.id || index,
                        type: item.type || 1, // 类型，1dtg，2emb
                        surface_name: item.surface_name, // 画板名称
                        canvas_name: item.canvas_name, // 画板名称
                        mask_image: item.mask_image, // 遮罩图片，宽度高度与容器一至
                        outer_width: item.outer_width || 2048, // 容器宽度
                        outer_height: item.outer_height || 2048, // 容器高度
                        real_width: item.real_width, // 容器宽度
                        real_height: item.real_height, // 容器高度
                        canvas_zoom: item.canvas_zoom,
                        canvas_left: item.canvas_left, // 画板相对容器的左边的位置
                        canvas_top: item.canvas_top, // 画板相对容器的左边的位置
                        canvas_width: item.canvas_width, // 画板的宽度
                        canvas_height: item.canvas_height, // 画板的宽度
                        canvas_rotate: item.canvas_rotate, // 画板旋转角度
                        price: item.price || 0, // 设计面价格
                        emb_zoom: item.emb_zoom || 1,
                        layers: [],
                        platens: [],
                        optional_platens: [],
                    };

                    try {
                        if (Array.isArray(item.layers)) {
                            piece.layers = item.layers;
                        } else {
                            piece.layers = JSON.parse(item.layers || '[]');
                        }
                    } catch (err) {
                        console.log(err);
                    }


                    // 刺绣
                    if (piece.type == 2) {

                        // piece.range = {
                        //     width: piece.canvas_width,
                        //     height: piece.canvas_height,
                        //     left: piece.canvas_left,
                        //     top: piece.canvas_top,
                        //     rotate: piece.canvas_rotate,
                        //     zoom: piece.canvas_zoom,
                        // }

                        try {
                            if (Array.isArray(item.platens)) {
                                piece.layers = item.platens;
                            } else {
                                piece.layers = JSON.parse(item.platens || '[]');
                            }

                            piece.layers = piece.layers.map(layer => {
                                return {
                                    type: 'emb',
                                    platens_id: layer.platens_id || '',
                                    name: layer.name || 0,
                                    w: layer.width || 0,
                                    h: layer.height || 0,
                                    x: layer.left || 0,
                                    y: layer.top || 0,
                                    rotate: layer.rotate || 0,
                                    product_dist: '',
                                    product_preview: layer.product_preview,
                                    product_colors: layer.product_colors,
                                    stitches_count: layer.stitches_count,
                                    price: layer.price || 0,
                                    scale: piece.emb_zoom || 1,
                                    dists: layer.dists || []
                                }
                            })

                        } catch (err) {
                            console.log(err);
                        }

                        try {
                            if (Array.isArray(item.optional_platens)) {
                                piece.optional_platens = item.optional_platens;
                            } else {
                                piece.optional_platens = JSON.parse(item.optional_platens || '[]');
                            }

                        } catch (err) {
                            console.log(err);
                        }

                    }

                    return piece;
                });

                // 模特列表
                let model_list = (data.model_list || []).map((model, index) => {
                    let mapping = model.mapping
                        ? JSON.parse(model.mapping || "[]")
                        : {};
                    let mapping_type = Object.prototype.toString.call(mapping);
                    let is_array = mapping_type == "[object Array]";
                    let is_object = mapping_type == "[object Object]";


                    // 字段名都改变了，这里要特别注意！！！！！
                    mapping = is_array ? mapping : is_object ? [mapping] : [];
                    mapping = mapping.map((mapper) => {
                        // factor 设置默认值
                        return {
                            type: mapper.type || 1,
                            canvas_name: mapper.canvas_name,
                            height: mapper.height,
                            width: mapper.width,
                            rotate: mapper.rotate,
                            x: mapper.x,
                            y: mapper.y,
                            clip: mapper.clip || "",
                            variant_deform:
                                parseFloat(mapper.variant_deform) || 0,
                            variant_factor:
                                parseFloat(mapper.variant_factor) || 0,
                        };
                    });

                    return {
                        id: model.id,
                        surface_name: model.surface_name, // 画板名称
                        mask_image: model.mask_image, // 遮罩图片，宽度高度与容器一至
                        mask_opacity: model.mask_opacity || 0, // 遮罩透明度，默认为0
                        mask_color: model.mask_color || '', // 遮罩颜色，默认为空字符
                        model_type: model.model_type || 1, // 1旧版，2新版
                        model_tag: model.model_tag || 'hanging',
                        model_name: model.model_name || 'Hanging',
                        model_color: model.model_color || '{}',
                        outer_width: model.outer_width || 2048, // 容器宽度
                        outer_height: model.outer_height || 2048, // 容器高度
                        mapping_top: !!model.mapping_top, // 设计区是否置顶
                        mapping: mapping.filter(i => i.type == 1).concat(mapping.filter(i => i.type != 1)),
                    };
                });


                // model_tag 要判断是否存在
                let tag = (tid ? data.model_tag : data.user_model_tag) || 'hanging';
                let tag_able = ['hanging', 'flat lay', 'model'].filter(i => model_list.find(model => model.model_tag == i))

                let piece_sort = piece_list.filter(i => i.type == 1).concat(piece_list.filter(i => i.type != 1)); // 排序，emb在最上层
                let piece_active = piece_sort.find(i => i.layers.length > 0) || piece_sort.find(i => i.type == 1)


                // store 参数
                let option = {
                    color_index: 0,
                    model_index: 0,
                    piece_index: Math.max(0, piece_sort.indexOf(piece_active)),
                    colors: color_list,
                    pieces: piece_sort,
                    models: model_list,
                    model_tag: tag_able.indexOf(tag) >= 0 ? tag : tag_able[0],
                    platens: data.platens_opt || [],
                    necklabelInfo: {
                        active: data.brand_label_id,
                        type: '',
                        cache: null,
                        list: []
                    }
                };


                // 当前选中的设计区
                let activePiece = option.pieces[option.piece_index];
                // 根据设计区选中的模特
                let activeModel = option.models.find((i) => i.surface_name == activePiece.surface_name && i.model_tag == option.model_tag);
                // 选中的颜色
                let activeColor = option.colors.find((i) => i.color_num == data.show_color_num || i.color_id == data.show_color_num) || option.colors[0];

                option.model_index = option.models.indexOf(activeModel || option.models[0]);
                option.color_index = option.colors.indexOf(activeColor || option.colors[0]);


                // 如果使用品牌领标
                if (data.brand_label_id) {

                    const pieceFormat = (pieceStr) => {
                        let result = pieceStr;

                        if (typeof pieceStr === "string") {
                            try {
                                result = JSON.parse(pieceStr);
                            } catch (err) {
                                console.log(err);
                            }
                        }
                        if (typeof result.layers === "string") {
                            try {
                                result.layers = JSON.parse(result.layers);
                            } catch (err) {
                                console.log(err);
                            }
                        }

                        result.type = 1;
                        return result;
                    };

                    const piece = option.pieces.filter(
                        (i) => i.canvas_name == "Neck Label Inner"
                    );
                    const price = (piece[0] || {}).price || 0;
                    const brandlabel = {
                        title: 'necklabel',
                        id: data.brand_label_id,
                        light: pieceFormat(data.brand_label_design),
                        dark: pieceFormat(data.dark_brand_label_design),
                    }

                    brandlabel.dark.price = price;
                    brandlabel.light.price = price;
                    option.necklabelInfo.active = data.brand_label_id;
                    option.necklabelInfo.type = ''; // 初始化时，不设置
                    option.necklabelInfo.list = [brandlabel]

                }



                setTimeout(() => this.$store.dispatch('designer/getNecklabelList'), 1);

                this.spu = data.spu || 0;
                this.title = data.title || "";
                this.product_id = data.product_id || 0;
                this.template_id = tid;
                this.sizes_list = (data.size_price || []).sort((a, b) => a.sort - b.sort);
                this.levelInfo = {
                    user_level: data.user_level,
                    user_discount: data.user_discount,
                }


                this.setInfoToStore(option);

                // 初始化完成后，先加载模特图、设计图
                // 有tid，表示二次编辑,加载全部字体
                const store = this.$store.state.designer || {}
                DesignManager.init({
                    pieces: store.pieces || [],
                    models: store.models || [],
                    colors: store.colors || [],
                    isedit: !!tid,
                }).then((e) => {
                    this.initing = false;
                    this.callback && this.callback(true)
                }).catch((error) => {
                    // this.initing = error;
                    this.initing = false;
                    this.callback && this.callback(true)
                });

            } else {
                this.initing = result.msg;
            }

        },

        // 获取最近使用的版带
        async getRecentlyUploadUsed () {
            if (!this.isLogin) {
                // 未登录
            } else {
                let response = await this.$http("Material.getEmbUploadUsed/5", {});
                this.recently_upload = (response.data || []).slice(0, 5)
            }
        },


        // 获取最近使用的文字版带
        async getRecentlyTextUsed () {
            if (!this.isLogin) {
                // 未登录
            } else {
                let response = await this.$http("Material.getEmbTextUsed", {});
                this.recently_text = (response.data || []).slice(0, 5)

            }
        },

        // 获取设计器信息
        setInfoToStore (option) {


            /*
            // 每次都是重新开始
            // 所以下面的都注释掉
            if(option.template_id){

              // 模板数据，重新加载的
              if(store.template_id == option.template_id){
                // 重新设计，且刷新
                option.pieces = store.pieces || [];
                color_index = Math.max(store.activeColor || 0,0);
                model_index = Math.max(store.activeModel || 0,0);
                piece_index = Math.max(store.activePiece || 0,0);
              }else{
                // 重新设计，非刷新
                option.pieces.map(piece=>{
                  piece.layers.map((layer,index)=>{layer.id = index;});
                });
              }

            }else if(option.product_id && store.product_id == option.product_id){

              // 新设计，且刷新
              let pieces = Object.fromEntries((store.pieces || []).map(piece=>{
                return [piece.surface_name,piece]
              }));

              option.pieces.map(piece=>{
                piece.layers = (pieces[piece.surface_name] || {}).layers || []
                piece.layers.map((layer,index)=>(layer.id = index));
              });
              color_index = Math.max(store.activeColor || 0, 0);
              model_index = Math.max(store.activeModel || 0, 0);
              piece_index = Math.max(store.activePiece || 0, 0);
            }
            */



            this.$store.commit("designer/SET_COLORS", option.colors);
            this.$store.commit("designer/SET_MODELS", option.models);
            this.$store.commit("designer/SET_PIECES", option.pieces);
            this.$store.commit("designer/SET_PLATENS", option.platens);
            this.$store.commit("designer/SET_NECKLABEL_INFO", option.necklabelInfo);

            this.$store.commit("designer/SET_ACTIVE_COLOR", option.colors[option.color_index]);
            this.$store.commit("designer/SET_ACTIVE_PIECE", option.pieces[option.piece_index]);

            this.$store.commit("designer/SET_ACTIVE_MODEL_TAG", option.model_tag);
            this.$store.commit("designer/SET_ACTIVE_MODEL", option.models[option.model_index]);


            this.setCache();
        },

        // 检查登录
        checkLogin () {
            if (this.isLogin) {
                return Promise.resolve();
            } else {
                return new Promise((resolve, reject) => {
                    this.$emit("global:userSignup", (e) => resolve());
                })
            }

        },

        // 生成预览图
        getDstThumb (stitches, line_color) {

            const codes = line_color.split(',').filter(i => i)
            const colorFormat = codes.map(i => colors.find(c => c.code == i)).filter(i => i)
            const canvas = writeCanvas(getStitchesByBase64(stitches), colorFormat)
            const email = (this.userInfo || {}).email;
            const folder = email ? Md5(email) : 'noemail';
            const path = ('data/pod/file/' + folder).replace(/\/+$/, '') + '/';

            const time = new Date().getTime();
            const random = Math.random().toFixed(10).substring(2);

            return new Promise((resolve, reject) => {
                canvas.toBlob(blob => {
                    const request = {
                        file: blob,
                        name: time + "-" + random + ".png",
                        path: path,
                    };
                    this.$uploadToOSS(request, response => {
                        if (response.code === 0 && response.data) {
                            resolve(response.data || '');
                        } else {
                            reject(response.msg || "Please check your network connection and try again.");
                        }
                    })

                }, "image/png", 1)
            })
        },


        // 绑定用户图片
        bindFiles (isLogin) {

            // 绑定用户图片
            const bindUser = () => {
                const binding = {
                    dtg_data: [],
                    emb_data: [],
                } // 绑定
                const dtg_uploaded = this.$refs.dtg_file_dialog.uploaded || []
                const emb_uploaded = this.$refs.emb_file_dialog.uploaded || []

                // 保存前未登录，需要先绑定图片和版带
                // this.$refs.saving.status = 'saving';

                this.pieces.map(piece => {
                    piece.layers.map(layer => {

                        if (layer.type == 'image') {
                            const media = dtg_uploaded.find(i => i.img_url == layer.url)
                            const active = media ? binding.dtg_data.find(i => i.file_url == media.img_url) : undefined;
                            // 存在，且去重
                            media && !active && binding.dtg_data.push({
                                folder_id: media.folder_id,
                                file_name: media.img_name,
                                file_url: media.img_url,
                                file_size: media.img_size,
                                width: media.width,
                                height: media.height,
                                img_type: media.img_type,
                                preview_url: media.preview_url,
                            })
                        }

                        if (piece.type == 2 && layer.dists && layer.dists.length > 0) {

                            layer.dists.map(dst => {

                                if (dst.type == 'upload' && dst.dst_id == 0) {
                                    const media = emb_uploaded.find(i => i.stitches == dst.stitches)
                                    const active = media ? binding.emb_data.find(i => i.stitches == media.stitches) : undefined;
                                    media && !active && binding.emb_data.push({
                                        file_name: media.file_name,
                                        file_url: media.file_url,
                                        file_type: media.file_type,
                                        img_url: media.img_url,
                                        width: media.width,
                                        height: media.height,
                                        left: media.left,
                                        top: media.top,
                                        right: media.right,
                                        bottom: media.bottom,
                                        line_color: dst.line_color,
                                        stitches_count: media.stitches_count,
                                        stitches: media.stitches,
                                        color_unedited: 1,
                                    })

                                }
                            })
                        }

                    })
                })

                if (binding.dtg_data.length > 0 || binding.emb_data.length > 0) {
                    // 保存
                    this.$refs.saving.option = {};
                    this.$refs.saving.status = 'saving';

                    return Promise.all(binding.emb_data.map(dst => this.getDstThumb(dst.stitches, dst.line_color))).then(res => {
                        res.map((url, idx) => binding.emb_data[idx].img_url = url)
                        return Promise.resolve()

                    }).then(res => {
                        const request = {
                            dtg_data: JSON.stringify(binding.dtg_data),
                            emb_data: JSON.stringify(binding.emb_data),
                        }
                        this.$http('Material.addBatchBinding', request)

                    }).then(res => {

                        const data = res.data || {};
                        const dtg_map = new Map((data.dtg_data || []).map(i => [i.file_url, i.id]))
                        const emb_map = new Map((data.emb_data || []).map(i => [i.file_url, i.id]))

                        binding.emb_data.map(dst => dst.id = dst.id || emb_map.get(dst.file_url) || '')
                        this.pieces.map(piece => {
                            piece.layers.map(layer => {
                                if (piece.type == 2 && layer.dists && layer.dists.length > 0) {
                                    layer.dists.map(dst => {
                                        if (dst.type == 'upload' && dst.dst_id == 0) {
                                            dst.dst_id = (binding.emb_data.find(i => i.stitches == dst.stitches) || {}).id || ''
                                        }
                                    })
                                }
                            });
                        });

                        this.$refs.saving.option = null;
                        this.$refs.saving.status = '';

                    }).catch(err => {
                        this.$refs.saving.option = null;
                        this.$refs.saving.status = '';
                    })
                } else {
                    return Promise.resolve()
                }
            }


            if (isLogin) {
                // 更新版带
                return Promise.resolve()
            } else {
                return bindUser()
            }

        },

        // 更新用户版带
        updateEmb (isLogin) {


            let change = false;

            // 更新文字最近使用
            const updateTxtRecently = () => {
                // 线色已经在updateDst自动更新，所以只用更新文字就行了
                const texts = []

                this.pieces.map(piece => {
                    piece.layers.map(layer => {
                        if (piece.type == 2 && layer.dists && layer.dists.length > 0) {
                            layer.dists.map(dst => dst.type == 'text' && texts.push(dst))
                        }
                    })
                })

                if (texts.length > 0) {

                    change = change || true;

                    return Promise.all(texts.slice(0, 3).map(dst => {
                        const option = {
                            line_color: dst.line_color,
                            stitches: dst.stitches,
                            stitches_count: dst.stitches_count,
                            dst_width: dst.dst_width, // 单位是0.1mm
                            dst_height: dst.dst_height, // 单位是0.1mm
                            font_text: dst.font_text || '', // 文字内容
                            font_envelop: dst.font_envelop || '', // 文字变形
                            font_arc: dst.font_arc || 0, // 文字弧度
                            font_size: dst.font_size || 0, // 文字大小
                            font_family: dst.font_family || '', // 字体
                        }
                        return this.$http("Material.addEmbTextUsed", option)
                    }))
                }
            }

            // 更新线色
            const updateDstColor = () => {
                const list = []
                this.pieces.map(piece => {
                    piece.layers.map(layer => {
                        if (piece.type == 2 && layer.dists && layer.dists.length > 0) {
                            layer.dists.map(dst => dst.type == 'upload' && dst.dst_id > 0 && !list.find(i => i.dst_id == dst.dst_id) && list.push(dst))
                        }
                    })
                })

                if (list.length > 0) {

                    change = change || true;

                    return Promise.all(list.map(dst => {
                        return this.getDstThumb(dst.stitches, dst.line_color)
                    })).then(res => {
                        const emb = list.map((dst, index) => ({
                            id: dst.dst_id,
                            img_url: res[index],
                            line_color: dst.line_color,
                            color_unedited: 1
                        }))
                        return this.$http('Material.setBatchUpdate', { emb_data: JSON.stringify(emb) })
                    })
                } else {
                    return Promise.resolve()
                }
            }

            // 上传的版带最近使用
            const updateDstRecently = () => {
                const recently = []

                this.pieces.map(piece => {
                    piece.layers.map(layer => {
                        if (piece.type == 2 && layer.dists && layer.dists.length > 0) {
                            layer.dists.map(dst => dst.type == 'upload' && dst.dst_id > 0 && recently.push(dst))
                        }
                    })
                })

                if (recently.length > 0) {
                    change = change || true;
                    return Promise.all(recently.slice(0, 5).map(dst => {
                        this.$http("Material.addEmbUploadUsed/" + dst.dst_id, {})
                    }))
                }
            }


            // 更新最近使用
            const getRecently = () => {
                return Promise.resolve()
            }

            // if (isLogin) {
            //     return Promise.all([updateTxtRecently(), updateDstColor()]).then(res => getRecently)
            // } else {
            //     return Promise.all([updateTxtRecently(), updateDstRecently()]).then(res => getRecently)
            // }


            if (isLogin) {
                return updateDstColor()
            } else {
                return Promise.resolve()
            }
        },

        // 保存设计信息
        async saveDraft (callback) {
            // 01.判断是否有设计，没有设计不保存
            // 02.判断图片是否有不高清的，如果不高清，则弹出提示图片不高清
            // 03.选择是购买还是同步到店铺
            // 04.如果选择购买，则弹出选择样品订单或商店订单
            // 05.如果选择发布，则弹出选择发布的商店
            // 06.跳转到对应的界面
            // 检查像素重叠

            const isLogin = this.isLogin;

            return this.$refs.overlap.check()
                .then(result => this.$refs.clarity.check())
                .then(result => this.checkLogin())
                .then(result => this.bindFiles(isLogin))
                .then(result => {

                    if (this.canLeave() && this.template_id) {
                        // 用户重新设计的，而且没有改，直接跳过生成
                        this.$router.push("/user/template");
                    } else {
                        // 保存对话框
                        const option = {
                            spu: this.spu, // 商品spu
                            product_id: this.product_id, // 产品id
                            template_id: this.template_id, // 模板id，如果是二次编辑，这个值才会有
                            brand_label_id: (this.necklabelInfo || {}).active || '', // 如果有选中了领标
                            color_id: (this.activeColor || {}).color_id || "", // 选中的颜色
                            pieces: this.pieces, // 设计面信息
                            models: this.models, // 模特信息
                            model_tag: this.activeModelTag,
                            platens: this.platens,
                        };
                        this.$refs.saving.doSaving(option, callback)

                        // 更新线色等操作都是异步的
                        this.updateEmb(isLogin)
                        // 异步重新加载资源
                        if (!isLogin) {
                            this.getRecentlyUploadUsed()
                            this.getRecentlyTextUsed()
                            this.$emit('global:DESIGN_MEDIA_LOGIN')
                        }
                        // return new Promise((res, rej) => this.$refs.saving.doSaving(option, (data) => data ? res(data) : rej('cancel')))
                    }

                }).catch(error => {
                    console.log(error);
                    // 取消了
                    // return Promise.reject(error)
                    // console.log(error);
                    callback && callback()
                })

        },

        // 切换款式
        changeShape () {

            // 保存提醒
            this.$refs.switch.check().then(res => {
                if (res == 'save') {
                    // 保存数据
                    return new Promise((res, rej) => {
                        this.saveDraft((result) => {
                            if (result) {
                                this.$uxMessage.success("Product template saved successfully.");
                                this.$refs.saving.close()
                                this.setCache();
                                res()
                            } else {
                                rej('cancel')
                            }
                        })
                    })
                } else {
                    return Promise.resolve()
                }
            }).then(res => {
                // 选择商品、选择替换方式是联动的
                const doApply = (cb) => {

                    const option = {
                        spu: '',
                        apply: '',
                        necklabel: JSON.parse(JSON.stringify((this.necklabelInfo || {}))),
                        pieces: JSON.parse(JSON.stringify(this.pieces))
                    }

                    this.$refs.products.open((spu) => {
                        if (spu) {
                            option.spu = spu;
                            this.$refs.apply.check().then(apply => {
                                option.apply = apply;
                                cb(option)
                            }).catch(err => doApply(cb))
                        } else {
                            // 取消了
                            cb();
                        }
                    })
                }
                return new Promise((res, rej) => doApply(opt => opt ? res(opt) : rej('cancel')))
            }).then(option => {

                // 替换路由
                if (option.spu != this.spu) {
                    this.$router.replace({ query: { pid: option.spu } }).catch(err => console.log(err))
                }

                // 重新获取数据
                this.getData({ pid: option.spu }, () => {

                    if (option.apply == 'replace') {
                        // 替换图层
                        this.pieces.map(piece => {
                            const place = option.pieces.find(p => p.canvas_name == piece.canvas_name && p.type == piece.type)
                            const layers = place && place.layers ? place.layers.slice(0) : []

                            if (layers.length > 0) {

                                // 对角线
                                const diagonal1 = Math.sqrt(Math.pow(piece.canvas_width, 2), Math.pow(piece.canvas_height, 2))
                                const diagonal2 = Math.sqrt(Math.pow(place.canvas_width, 2), Math.pow(place.canvas_height, 2))
                                const scale = diagonal1 / diagonal2 || 1;
                                // const scale = 1;

                                layers.map(layer => {

                                    if (piece.type == 2) {
                                        // 刺绣

                                        if (piece.optional_platens.find(i => i.code == layer.platens_id)) {
                                            // 必须包含这个框才添加
                                            const emb_zoom = piece.emb_zoom || 1
                                            const scale = piece.canvas_zoom / emb_zoom;
                                            const platen = this.platens.find(i => i.code == layer.platens_id)

                                            piece.layers.push({
                                                ...layer,
                                                w: platen.width * scale,
                                                h: platen.height * scale,
                                                x: piece.canvas_width * layer.x / place.canvas_width,
                                                y: piece.canvas_height * layer.y / place.canvas_height,
                                                scale: emb_zoom || 1,
                                                dists: layer.dists.map(dst => ({
                                                    ...dst,
                                                    w: scale * 300 * dst.dst_width / 254, // 图片最终显示宽度, mm转英寸转300dpi之后缩放
                                                    h: scale * 300 * dst.dst_height / 254, // 图片最终显示调试, mm转英寸转300dpi之后缩放
                                                }))
                                            })
                                        }

                                    } else {
                                        // 中心点偏移
                                        const offsetX = scale * (layer.x + 0.5 * layer.w - 0.5 * place.canvas_width)
                                        const offsetY = scale * (layer.y + 0.5 * layer.h - 0.5 * place.canvas_height)

                                        const w = layer.w * scale;
                                        const h = layer.h * scale;

                                        const x = 0.5 * piece.canvas_width - 0.5 * w + offsetX;
                                        const y = 0.5 * piece.canvas_height - 0.5 * h + offsetY;

                                        // 文字，改字号
                                        if (layer.type == 'text') {
                                            piece.layers.push({ ...layer, w: w, h: h, x: x, y: y, font_size: layer.font_size * scale })
                                        } else {
                                            piece.layers.push({ ...layer, w: w, h: h, x: x, y: y })
                                        }
                                    }

                                })
                                // piece.layers.splice(0, piece.layers.length, ...replace)
                            }
                        })

                        if (option.necklabel.active) {
                            const active = option.necklabel.list.find(i => i.id == option.necklabel.active)
                            const necklabel = { ...option.necklabel, active: '' }

                            this.$store.commit("designer/SET_NECKLABEL_INFO", necklabel);
                            this.$store.commit("designer/SET_NECKLABEL_ACTIVE", active);
                        }

                    } else {
                        // 不替换，不管
                    }

                    this.$uxMessage.success("Product switched successfully.");
                })


                // .then(res => {

                // }).catch(error => {
                //     this.$uxMessage.error("Failed to switch product.");
                //     return Promise.reject(error)
                // })

            }).catch(err => {
                console.log(err)
            })
        },


        // 设置缓存
        setCache () {
            this.cache = JSON.stringify({
                color: this.activeColor,
                pieces: this.pieces,
                model_tag: this.activeModelTag
            });
        },
        // 检查缓存
        checkCache () {
            const cache = JSON.stringify({ color: this.activeColor, pieces: this.pieces, model_tag: this.activeModelTag });
            return cache == this.cache
        },


        // 是否可以离开
        canLeave () {
            let design = this.pieces.map((piece) => {
                return piece.layers.length > 0;
            });
            if (design.length == 0) {
                // 所有设计为空可离开
                return true;
            } else if (this.checkCache()) {
                // 和缓存相同可离开
                return true;
            } else {
                return false;
            }
        },

        // 清空数据
        clearDesign () {
            this.$store.commit("designer/SET_ACTIVE_LAYER", null);
            this.pieces.map((piece) =>
                piece.layers.splice(0, piece.layers.length)
            );
            this.$emit("global:DESIGN_CLEANUP");
            this.setCache();
        }
    },
    created () {
        this.$on("global:DESIGN_EMB_DBLCLICK", () => this.handlerScale());
        this.$on("global:DESIGN_LOAD_RECENTLY_EMB", () => this.getRecentlyUploadUsed());
        this.$on("global:DESIGN_LOAD_RECENTLY_TXT", () => this.getRecentlyTextUsed());

        if (process.client) {
            this.getData(this.$route.query || {});
            this.getRecentlyUploadUsed();
            this.getRecentlyTextUsed();

            window.onbeforeunload = (event) => {
                let notify = "Changes that you made may not be saved.";
                if (this.canLeave()) {
                } else {
                    (event || window.event).returnValue = notify;
                    return notify;
                }
            };
        }
    },
    beforeDestroy () {
        // 清空数据
        this.$store.commit("designer/SET_COLORS", []);
        this.$store.commit("designer/SET_MODELS", []);
        this.$store.commit("designer/SET_PIECES", []);
        this.$store.commit("designer/SET_ACTIVE_COLOR", null);
        this.$store.commit("designer/SET_ACTIVE_PIECE", null);
        this.$store.commit("designer/SET_ACTIVE_MODEL", null);
    },

    // 路由离开
    beforeRouteLeave (to, from, next) {
        // 导航离开该组件的对应路由时调用

        if (this.canLeave()) {
            this.clearDesign();
            window.onbeforeunload = null;
            next();
        } else {
            next(false);
            this.$refs.leave.check(() => {
                this.clearDesign();
                window.onbeforeunload = null;
                next();
            })
        }
    },
};
</script>

<style lang="scss" scoped>
.designer {
    display: flex;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    bottom: 0;
    z-index: 10;
}

.designer-init {
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9;
    background: #fff;

    p {
        width: 400px;
        text-align: center;
        text-align: center;
        line-height: 36px;
        font-size: 24px;

        strong {
            display: block;
            font-weight: normal;
        }

        button {
            position: relative;
            margin-top: 20px;
            height: 32px;
            line-height: 32px;
            padding: 0 17px;
            font-size: 12px;
            background: #ffffff;
            border-radius: 16px;
            border: 1px solid #d9d9d9;
            white-space: nowrap;
            box-sizing: border-box;
            background: #fff;
            font-weight: normal;
        }

        img {
            width: 120px;
            height: 60px;
        }

        em {
            display: block;
            height: 30px;
            font-size: 21px;

            font-weight: normal;
            color: #000000;
            line-height: 30px;
        }
    }
}

.layout-ready {
    display: flex;
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    right: 0;
}

.layout-render {
    flex: 640;
    padding: 72px 20px 32px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;

    &:after {
        content: '';
        position: absolute;
        right: 0;
        top: 0;
        width: 1px;
        height: 100%;
        background: #e6e6e6;
    }

    .layout-render-name {
        width: 100%;
        height: 40px;
        min-height: 40px;
    }

    .layout-render-tag {
        margin-top: 26px;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .layout-render-preview {
        width: 100%;
        margin: 16px 0;
        box-sizing: border-box;
        position: relative;
        overflow: hidden;

        &:before {
            content: '';
            display: block;
            padding-bottom: 100%;
            height: 0;
        }
    }

    .layout-render-models {
        width: 100%;
        margin-top: 18px;
    }

    .layout-render-color {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .layout-render-price {
        margin-top: 20px;
    }
}

.layout-content {
    padding-top: 62px;
    flex: 1280;
    position: relative;
    display: flex;
}

.layout-editor {
    display: flex;
    flex-direction: column;
    flex: 830;
    position: relative;
    overflow: hidden;
    justify-content: space-between;

    .layout-editor-pieces {
        position: relative;
        width: 100%;
        margin-top: 6px;
        min-height: 32px;
        z-index: 3;
    }

    .layout-editor-flex {
        flex: 1;
        position: relative;
        padding: 20px 20px 20px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        overflow: hidden;
    }

    .layout-editor-panel {
        position: relative;
        width: 100%;
        overflow: hidden;

        position: relative;
        overflow: hidden;

        &:before {
            content: '';
            display: block;
            padding-bottom: 100%;
            height: 0;
        }
    }

    .layout-editor-button {
        margin-top: 2px;
        height: 40px;
        min-height: 40px;
        pointer-events: none;
        display: flex;
        justify-content: center;
        z-index: 1;

        button {
            margin: 0 8px;
            pointer-events: all;
            position: relative;
            width: 36px;
            height: 36px;
            box-sizing: border-box;
            border: 1px solid transparent;
            border-radius: 4px;

            svg {
                position: absolute;
                left: 50%;
                top: 50%;
                transform: translate(-50%, -50%);
                width: 22px;
                height: 22px;
                color: #555;
                pointer-events: none;
            }

            &.active {
                background: #f6f6f6;

                svg {
                    color: #ea4c89;
                }
            }

            &:hover {
                border-color: #808080;
            }
        }
    }
}

.layout-tooler {
    width: 320px;
    display: flex;
    flex-direction: column;
    position: relative;
    max-width: 350px;
    min-width: 260px;
    border-left: 1px solid #e6e6e6;

    .layout-tooler-panel {
        border-bottom: 1px solid #f0f0f0;
        flex: 1;
        position: relative;
    }

    .layout-tooler-save {
        margin: 16px 45px;

        button {
            width: 100%;
            height: 44px;

            &[disabled] {
                border-color: #e0e0e0;
                background-color: #f6f6f6;
                color: #9e9e9e;
            }
        }
    }
}

.layout-footer {
    position: absolute;
    width: 23.44%;
    right: 0;
    bottom: 0;
    display: flex;
    box-sizing: border-box;
    padding: 0 45px;
    height: 110px;
    justify-content: center;
    align-items: center;

    &:before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        width: 1px;
        height: 100%;
        background: #f2f2f2;
    }
}
</style>
